package com.example.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplus.common.utls.SessionUtils;
import com.example.mybatisplus.mapper.LearnupMapper;
import com.example.mybatisplus.model.domain.Learn;
import com.example.mybatisplus.mapper.LearnMapper;
import com.example.mybatisplus.model.domain.Learnup;
import com.example.mybatisplus.model.domain.Reportup;
import com.example.mybatisplus.model.domain.Userlist;
import com.example.mybatisplus.model.dto.PageDTO;
import com.example.mybatisplus.service.LearnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatisplus.service.LearnupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 工作上报 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2023-01-07
 */
@Service
public class LearnServiceImpl extends ServiceImpl<LearnMapper, Learn> implements LearnService {

    @Autowired
    private LearnMapper learnMapper;

    @Autowired
    private LearnupMapper learnupMapper;

    @Autowired
    private LearnupService learnupService;

    @Autowired
    private LearnService learnService;

    @Override
    public void rep(Learn learn) {
        Userlist curUser = SessionUtils.getCurUser();
        learn.setName(curUser.getName());
        learn.setUserId(curUser.getId());
        learn.setLevel(curUser.getLevel());
    }

    @Override
    public void insert(Learn learn) {
        learnMapper.insert(learn);
        List<Learnup> learnups = learn.getPaths().stream().map(s ->
                new Learnup().setPath(s).setLearnId(learn.getId()))
                .collect(Collectors.toList());
        learnupService.saveBatch(learnups);
    }


    @Override
    public Page<Learn> listPage(Learn learn, PageDTO pageDTO) {
        Page<Learn> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        QueryWrapper<Learn> wrapper = new QueryWrapper<>();
        learnMapper.selectPage(page, wrapper);

        for (Learn learn1 : page.getRecords()) {
            QueryWrapper<Learnup> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("learn_id", learn.getId());

            QueryWrapper<Learn> wrapper2 = new QueryWrapper<>();
            List<Learn> learns = learnService.list(wrapper2);

            Learnup learnup = learnupMapper.selectOne(wrapper1);
            if (learnup != null) {
                learn1.setPath(learnup.getPath());
                learn1.setLearns(learns);
            }
        }
        return page;
    }
}
